package main

import (
	"os"
	"path/filepath"
	"strings"
	"text/template"
)

type Generater func(suffix string, opt *Options, tmpl *template.Template) error

func preCheck(tmplList []string) error {
	err := opts.Preprocess()
	if err != nil {
		Logf("配置预处理错误 %v", err)
		return err
	}

	if PathExits(opts.outDir) == false {
		err := os.MkdirAll(opts.outDir, 0755)
		if err != nil {
			return err
		}
	}

	for idx := range tmplList {
		tmplList[idx], _ = filepath.Abs(tmplList[idx])
	}

	return nil
}

func doFileGen(tmplList []string, gf Generater) error {
	//切换到输出目录
	err := os.Chdir(opts.outDir)
	if err != nil {
		return err
	}

	for _, tmplFile := range tmplList {
		tmpl, err := getTemplate(tmplFile, "codegen")
		if err != nil {
			Logf("模板文件 %s 生成模板时发生错误 %v!", tmplFile, err)
			continue
		}
		tmplFile = filepath.Base(tmplFile)
		if len(opts.toFile) > 0 {
			tmplFile = opts.toFile
		}
		err = gf(tmplFile, &opts, tmpl)
		if err != nil {
			Logf("模板文件%s 执行出错 %v!", tmplFile, err)
			continue
		}
	}
	return nil
}

func onCodeAction(tmplList []string) error {

	err := preCheck(tmplList[:])
	if err != nil {
		Logf("%v", err)
	}

	//切换到输出目录
	err = os.Chdir(opts.outDir)
	if err != nil {
		return err
	}

	//检查idl目录
	idlPath := strings.ToLower(opts.jsonData.IdlName)
	if err := CheckIdlDir(idlPath); err != nil {
		Logf("checkout idl %s dir error %v ", idlPath, err)
		return err
	}

	// 切换到idl目录
	if err := os.Chdir(idlPath); err != nil {
		return err
	}

	for _, tmplFile := range tmplList {
		tmpl, err := getTemplate(tmplFile, "codegen")
		if err != nil {
			Logf("模板文件 %s 生成模板时发生错误 %v!", tmplFile, err)
			continue
		}
		tmplFile = filepath.Base(tmplFile)
		if len(opts.toFile) > 0 {
			tmplFile = opts.toFile
		}
		err = GenServiceFile(tmplFile, &opts, tmpl)
		if err != nil {
			Logf("模板文件%s 执行出错 %v!", tmplFile, err)
			continue
		}
	}

	return nil
}

func onDataAction(tmplList []string) error {
	err := preCheck(tmplList[:])
	if err != nil {
		Logf("%v", err)
	}

	return doFileGen(tmplList, GenDataFile)
}

func onTableAction(tmplList []string) error {
	err := preCheck(tmplList[:])
	if err != nil {
		Logf("%v", err)
	}

	return doFileGen(tmplList, GenTableFile)
}

func onEnumAction(tmplList []string) error {
	err := preCheck(tmplList[:])
	if err != nil {
		Logf("%v", err)
	}

	return doFileGen(tmplList, GenEnumFile)
}

// onSDKAction generate for sdk
func onSDKAction(tmplList []string) error {
	err := preCheck(tmplList[:])
	if err != nil {
		Logf("%v", err)
	}

	return doFileGen(tmplList, GenSdkFile)
}

func onPubAction(tmplList []string) error {
	err := opts.DealPath()
	if err != nil {
		Logf("配置预处理错误 %v", err)
		return err
	}

	if PathExits(opts.outDir) == false {
		err := os.MkdirAll(opts.outDir, 0755)
		if err != nil {
			return err
		}
	}

	for idx := range tmplList {
		tmplList[idx], _ = filepath.Abs(tmplList[idx])
	}

	return doFileGen(tmplList, GenPubgo)
}
